<extend name="Base/common"/>
<block name="style">
<link href="__PUBLIC__/Blovex4/css/jquery.datetimepicker.css" rel="stylesheet">
</block>

<block name="Content">
	<div class="am-cf am-padding-top">
        <div class="am-fl am-cf">
            <i class="am-icon-pencil-square-o"></i>
            <strong class="am-text-primary am-text-lg">
                    新增订单
            </strong>
        </div><hr data-am-widget="divider" class="am-divider am-divider-default" />
    </div>
    <div class="am-tabs" data-am-tabs>
        <ul class="am-tabs-nav am-nav am-nav-tabs">
            <li>
                <a href="#tab2">订单信息</a>
            </li>
        </ul>
        <div class="am-tabs-bd">
            <div class="am-tab-panel am-fade" id="tab2">
                <form class="am-form" method="post" action="{:U('Orders/saveAction')}">
                    <div class="am-g am-margin-top">
                        <div class="am-u-sm-4 am-u-md-2 am-text-right">
                            用户账号
                        </div>
                        <div class="am-u-sm-8 am-u-md-4 am-u-end col-end">
                            <input type="text" class="am-input-sm js-ajax-validate" name="account" id="account"
                            	  value="{$userModel['account']}" placeholder="用户注册手机号" required>
                            <input type="hidden" class="am-input-sm" name="user_id" id="user_id" value="{$userModel['user_id']}">
                        </div>
                        <div class="am-hide-sm-only am-u-md-6">
                        </div>
                    </div>
                    <div class="am-g am-margin-top">
                        <div class="am-u-sm-4 am-u-md-2 am-text-right">
                            服务类型
                        </div>
                        <div class="am-u-sm-8 am-u-md-4">
                            <select data-am-selected="{btnSize: 'sm', btnStyle: 'secondary',maxHeight: 200}" 
                            	name="detail_id" id="detail_id">
                                <foreach name="detailList" item="class">
                                    <optgroup label="{$class.class_name}">
                                    <notempty name="class['_child']">
                                        <foreach name="class['_child']" item="detail">
                                            <option value="{$detail.detail_id}" emergency="{$detail.emergency}">{$detail.detail_name}</option>
                                        </foreach>
                                    </notempty>
                                    </optgroup>
                                </foreach>
                            </select>
                        </div>
                        <div class="am-hide-sm-only am-u-md-6">
                        </div>
                    </div>
                    <div class="am-g am-margin-top">
                        <div class="am-u-sm-4 am-u-md-2 am-text-right">
                            预约类型
                        </div>
                        <div class="am-u-sm-8 am-u-md-4">
                            <select name="emergency" id="emergency" disabled>
                            	<option value="1" selected>预约服务</option>
                                <option value="2">紧急服务</option>
                            </select>
                        </div>
                        <div class="am-hide-sm-only am-u-md-6">
                        </div>
                    </div>
                    <div class="am-g am-margin-top" style="display:none;" id="delaydiv">
                        <div class="am-u-sm-4 am-u-md-2 am-text-right">
                            紧急时间
                        </div>
                        <div class="am-u-sm-8 am-u-md-4">
                            <select name="delay" id="delay">
                            	<option value="50" selected>50分钟</option>
                                <option value="40">40分钟</option>
                                <option value="30">30分钟</option>
                                <option value="20">20分钟</option>
                            </select>
                        </div>
                        <div class="am-hide-sm-only am-u-md-6">
                        </div>
                    </div>
                    
                    <div class="am-g am-margin-top" id="workerdiv">
                        <div class="am-u-sm-4 am-u-md-2 am-text-right">
                            指定小哥
                        </div>
                        <div class="am-u-sm-8 am-u-md-4 am-u-end col-end">
                            <input type="text" class="am-input-sm" name="eid" id="eid"
                            	  value="" placeholder="小哥工号">
                        </div>
                        <div class="am-hide-sm-only am-u-md-6">
                        </div>
                    </div>
                    <div class="am-g am-margin-top" id="appointdiv">
						<div class="am-u-sm-4 am-u-md-2 am-text-right">
                                预约时间:
                        </div>
                        <div class="am-u-sm-8 am-u-md-4 am-u-end col-end">
                            <input type="text" class="am-form-field am-input-sm" readonly="readonly"
                            	name="appointment" style="cursor:pointer;width:100%" 
                            	id="appointment" datetimepicker>
                        </div>
                        <div class="am-hide-sm-only am-u-md-6" id="timediv">
                        </div>
                    </div>
                    <div class="am-g am-margin-top">
                        <div class="am-u-sm-4 am-u-md-2 am-text-right">
                            维修地址
                        </div>
                        <div class="am-u-sm-8 am-u-md-4">
                            <select name="address_id" id="address_id">
                            	<option value="">请选择维修地址</option>
                                <foreach name="list" item="address">
                                    <option value="{$address.address_id}" contact="{$address.contact}" tel="{$address.telphone}"
                                    	address="{$address.address}"
                                    	<if condition="address.default_address eq '1'">selected </if>>
                                    	{$address.address}
                                    </option>
                                </foreach>
                                <option value="-1">其它</option>
                            </select>
                        </div>
                        <div class="am-hide-sm-only am-u-md-6">
                        </div>
                    </div>
                    <div class="am-g am-margin-top">
                        <div class="am-u-sm-4 am-u-md-2 am-text-right">
                            联系人姓名
                        </div>
                        <div class="am-u-sm-8 am-u-md-4">
                            <input type="text" class="am-input-sm" name="contact" id="contact" value="" required/>
                        </div>
                        <div class="am-hide-sm-only am-u-md-6">
                        </div>
                    </div>
                    <div class="am-g am-margin-top">
                        <div class="am-u-sm-4 am-u-md-2 am-text-right">
                            联系电话
                        </div>
                        <div class="am-u-sm-8 am-u-md-4">
                            <input type="text" class="am-input-sm" name="telphone" id="telphone"
                            	 pattern="^1(3|4|5|7|8)\d{9}$" value="" required/>
                        </div>
                        <div class="am-hide-sm-only am-u-md-6">
                        </div>
                    </div>
                    <div class="am-g am-margin-top">
                        <div class="am-u-sm-4 am-u-md-2 am-text-right">
                            详细地址
                        </div>
                        <div class="am-u-sm-8 am-u-md-4">
                        	<div class="am-input-group am-input-group-sm">
			                    <input type="text" class="am-form-field am-input-sm" 
			                    	placeholder="详细地址" name="address" id='address' value="" required/>
			                    <span class="am-input-group-btn">
			                        <button class="am-btn am-btn-default" type="button" onclick="codeAddress()">
			                            搜索
			                        </button>
			                    </span>
			                </div>
                        </div>
                        <div class="am-hide-sm-only am-u-md-6">
                        </div>
                    </div>
                    <div class="am-g am-margin-top">
                        <div class="am-u-sm-4 am-u-md-2 am-text-right">
                        </div>
                        <div class="am-u-sm-8 am-u-md-8">
                        	<div name="container" id="container" style="height:300px"></div>
                        </div>
                        <div class="am-hide-sm-only am-u-md-2">
                        </div>
                    </div>
                    <div class="am-margin">
                        <button type="submit" class="am-btn am-btn-success am-btn-xs ajax-post" target-form="am-form">
                            提交保存
                        </button>
                        <button type="button" class="am-btn am-btn-secondary am-btn-xs" onclick="javascript:history.back(-1);return false;">
                            返回列表
                        </button>
                        <input type="hidden" name="worker_id" id="worker_id" value="" />
                        <input type="hidden" name="province" id="province" value="{$addressModel['province']}" />
                        <input type="hidden" name="city" id="city" value="{$addressModel['city']}" />
                        <input type="hidden" name="district" id="district" value="{$addressModel['district']}" />
                        <input type="hidden" name="latitude" id="latitude" value="{$addressModel['latitude']|default='39.98752'}" />
                        <input type="hidden" name="longitude" id="longitude" value="{$addressModel['longitude']|default='116.41945'}" />
                    </div>
                </form>
            </div>
        </div>
    </div>
</block>
<block name="script">

<script type="text/javascript" src="__PUBLIC__/Common/js/map.js"></script>
<script type="text/javascript" src="__PUBLIC__/Common/js/jquery.datetimepicker.js"></script>
<script type="text/javascript">

window.onload = loadScript;

$(function() {
	
	Think.setValue('address_id', '{$address_id}');
	
	var timeList = [];
	
	$('.am-form').validator({
		validate: function(validity) {
			var v = $(validity.field).val();
			
			var comparer = function(data) {
				if(data.status == 0){
	    			validity.valid = false;
	    			$("#address_id option[value!='']").remove();
	    		}else{
	    			var html = '<option value="">请选择维修地址</option>';
	    			var checked = '';
	    			$.each(data.info, function(k,v){
	    				checked = v['default_address'] == '1' ? ' checked ' : '';
	    				html += '<option value="' + v['address_id'] + '" contact="' + v['contact'] + '" ';
	    				html += 'tel="' + v['telphone'] + '" address="' + v['address'] + '" ' + checked + '>';
	    				html += v['address'] + '</option>';
	    			});
	    			
	    			html += '<option value="-1">其它</option>';
	    			
	    			$("#address_id").html(html);
	    		}
			};
			
			var time = function(data){
				
				if(data.status == 0){
					
					validity.valid = false;
					$("#timeList").html('未查到小哥信息');
					$("#worker_id").val('0');
				}else{
					$("#timeList").html('');
					$("#appointment").val('');
					$("#worker_id").val(data.status);
				}
				
				$.each(data.info, function(k,v){
					$.each(v['timeList'], function(t, m){
						if(m['status'] == '4'){
							timeList.push('' + m['timestamp']);
						} 
					})
				});
			};
			
			// Ajax 验证注册账号是否存在
		    if ($(validity.field).is('.js-ajax-validate')) {
		    	var account = $("#account").val();
		    	var validityURL = Think.U('Orders/validity');
		    	
		    	if(!(/^1((3|4|5|8){1}\d{1}|70)\d{8}$/.test(account))){
		    		validity.valid = false;
		    	}else{
			    	return $.ajax({
			            url: validityURL,
			            cache: false,
			            data:{'account':account},
			            dataType: 'json'
			        }).then(function(data) {
			            comparer(data);
			            return validity;
			        }, function() {
			        	return validity;
			        });
		    	}
			}else if ($(validity.field).is('#eid')) {
				
				var eid = $("#eid").val();
				var workerURL = Think.U('Orders/queryWorker');
				
				if(eid != ""){
					
					return $.ajax({
			            url: workerURL,
			            cache: false,
			            data:{'eid':eid},
			            dataType: 'json'
			        }).then(function(data) {
			        	time(data);
			            return validity;
			        }, function() {
			        	return validity;
			        });
				}else{
					return true;
				}
			}else if ($(validity.field).is('#appointment')) {
				
				var timestamp = strTotimeStamp(v);

				if($.isArray(timeList) && timeList.length > 0 && $.inArray('' + timestamp, timeList) == -1){
					validity.valid = false;
					$("#timediv").html('预约时间有冲突，请重新选择时间');
				}else{
					$("#timediv").html('');
				}
			}
		},
		
		submit: function() {
			
		    var formValidity = this.isFormValid();

		    $.when(formValidity).then(function() {
		      // 验证成功的逻辑
		      alert('成功');
		    }, function() {
		      // 验证失败的逻辑
		      alert('失败');
		    });
		}
	});
	
	$("#address_id").change(function(){
		
		var val = $(this).children('option:selected').val();
		
		if(!isNaN(val)){
			
			var address = $(this).children('option:selected').attr('address');
			var contact = $(this).children('option:selected').attr('contact');
			var telphone = $(this).children('option:selected').attr('tel');
			
			$('#contact').val(contact);
			$('#telphone').val(telphone);
			$('#address').val(address);
		}
	});
	
	$("#detail_id").off('change').on('change', function(){
		var emergency = $(this).find('option').eq(this.selectedIndex).attr('emergency');
		
		if(emergency == 1){
			$("#emergency").removeAttr('disabled');
		}else{
			$("#emergency").val('1');
			$("#emergency").trigger('change');
			$("#emergency").attr('disabled', 'disabled');
		}
		
		return false;
	});
	
	$("#emergency").off('change').on('change', function(){
		
		var emergency = $(this).val();
		
		if(emergency == 1){
			$("#delaydiv").css('display', 'none');
			$("#workerdiv").css('display', 'block');
			$("#appointdiv").css('display', 'block');
			$("#eid").val('');
			$("#eid").trigger('change');
		}else{
			$("#eid").val('');
			$("#eid").trigger('change');
			$("#workerdiv").css('display', 'none');
			$("#appointdiv").css('display', 'none');
			$("#delaydiv").css('display', 'block');
		}
	});
	
	var timePicker = $("#appointment").datetimepicker({
        datepicker: true,
        startDate: new Date().toLocaleString(),
        format: 'Y-m-d H:i',
        step: 60,
        minView:1,
        lang:'ch'
    });
});

function formatDate(timeStamp){
	
	var localTime = new Date(timeStamp * 1000);
	var year = localTime.getFullYear();
	var month = parseInt(localTime.getMonth()) + 1;
	var date = localTime.getDate();

	return year + '.' + month + '.' + date;
}

function formatHour(timeStamp){
	
	var localTime = new Date(timeStamp * 1000);
	var hour = localTime.getHours();
	
	return checkTime(hour) + ':00';
}

function checkTime(i){
	if (i<10){
        i = "0" + i;
    }
    return i;
}

function strTotimeStamp(str) {
	var tempStrs = str.split(" ");
	var dateStrs = tempStrs[0].split("-");
	var year = parseInt(dateStrs[0], 10);
	var month = parseInt(dateStrs[1], 10) - 1;
	var day = parseInt(dateStrs[2], 10);
	var timeStrs = tempStrs[1].split("-");
	var hour = parseInt(timeStrs [0], 10);
	hour = isNaN(hour) ? 14 : hour;
	var date = new Date(year, month, day, hour, 0, 0);
	
	var timestamp = date.getTime().toString();
	return timestamp.substr(0, 10);
}
</script>

</block>